<template>
  <el-card class="box-card">
    <el-row :gutter="10" align="middle" justify="center" type="flex">
      <el-col :span="12">
        <div class="info-item">应收金额 <strong>￥{{ amountOfCartList.toFixed(2) }}</strong></div>
      </el-col>
      <el-col :span="3">
      </el-col>
      <el-col :span="3">
      </el-col>
      <el-col :span="3">
      </el-col>
      <el-col :span="3">
      </el-col>
    </el-row>
    <el-row :gutter="10" align="middle" justify="center" type="flex">
      <el-col :span="12">
        <div class="info-item">会员优惠 <span>-￥{{ systemDiscount.toFixed(2) }}</span></div>
      </el-col>
      <el-col :span="3">
      </el-col>
      <el-col :span="3">
      </el-col>
      <el-col :span="3">
      </el-col>
      <el-col :span="3">
      </el-col>
    </el-row>
    <el-row :gutter="10" align="middle" justify="center" type="flex">
      <el-col :span="12">
        <el-tooltip class="item" content="点我选券" effect="dark" placement="top-start">
          <div class="info-item coupon" @click="handleCouponDialogClick">优&nbsp;&nbsp;惠&nbsp;&nbsp;券
            <span>-￥{{ couponDiscountAmount }}</span> <i class="el-icon-arrow-right"></i></div>
        </el-tooltip>
      </el-col>
      <el-col :span="3">
      </el-col>
      <el-col :span="3">
      </el-col>
      <el-col :span="3">
      </el-col>
      <el-col :span="3">
      </el-col>
    </el-row>
    <el-row :gutter="10" align="middle" justify="center" type="flex">
      <el-col :span="12">
        <div class="info-item">实收金额 <span><strong>￥{{ cartPayAmount.toFixed(2) }}</strong></span></div>
      </el-col>
      <el-col :span="3">
      </el-col>
      <el-col :span="3">
      </el-col>
      <el-col :span="3">
      </el-col>
      <el-col :span="3">
      </el-col>
    </el-row>
    <el-row :gutter="10" align="middle" justify="center" type="flex">
      <el-col :span="12">
        <div class="info-item">油卡结余 ￥{{ cardBalanceAfterPay }}</div>
      </el-col>
      <el-col :span="4">
        <el-button icon="el-icon-delete" size="small" type="warning" @click="checkOthers">其&nbsp;&nbsp;他
        </el-button>
      </el-col>
      <el-col v-show="!showCancelSplitOrder" :span="4">
        <el-button icon="el-icon-scissors" size="small" type="danger" @click="handleSplitOrder">拆&nbsp;&nbsp;单
        </el-button>
      </el-col>
      <el-col v-show="showCancelSplitOrder" :span="4">
        <el-button size="small" type="danger" @click="cancelSplitOrder">撤销拆单</el-button>
      </el-col>
      <el-col :span="4">
        <el-button size="small" type="success" @click="showAmountCheckList">秒付历史</el-button>
      </el-col>
    </el-row>
    <el-row :gutter="10" align="middle" justify="center" type="flex">
      <el-col :span="12">
        <div class="info-item">收到现金 ￥{{ cartCash }} 找零 ￥{{ cashChange }}</div>
      </el-col>
      <el-col :span="4">
        <el-button size="small" type="warning" @click="checkBackToTank">回罐&nbsp;F10</el-button>
      </el-col>
      <el-col :span="4">
        <el-button size="small" type="danger" @click="checkSelfUse">自用&nbsp;F11</el-button>
      </el-col>
      <el-col :span="4">
        <el-button size="small" type="primary" @click="handlePending">挂单&nbsp;F12</el-button>
      </el-col>
    </el-row>
    <!-- 支付方式切换栏 -->
    <el-row :gutter="10" align="middle" justify="center" type="flex">
      <el-col :span="4">
        <div v-waves :class="{'forbidden' : isPoints || isCommonCard }" class="payway"
             @click="handlePayWayClick('paycode')">
          <div class="icon">
            <img alt="" src="@/assets/icons/paycode.svg">
          </div>
          <div class="name">支付码F3</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div v-waves :class="{'forbidden' : isPoints || isCommonCard }" class="payway"
             @click="handlePayWayClick('yinlian')">
          <div class="icon">
            <img alt="" src="@/assets/icons/yinlian.svg">
          </div>
          <div class="name">银联卡F4</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div v-waves :class="{'forbidden' : isPoints || isCommonCard }" class="payway"
             @click="handlePayWayClick('cash')">
          <div class="icon">
            <img alt="" src="@/assets/icons/cash.svg">
          </div>
          <div class="name">现金F6</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div v-waves :class="{'forbidden' : !isCommonCard || memberId || cartGoodsAmount || cartOilAmount <= 0 }"
             class="payway" @click="handlePayWayClick('oilcard')">
          <div class="icon">
            <img alt="" src="@/assets/icons/oilcard2.svg">
          </div>
          <div class="name">加油卡</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div v-waves :class="{'forbidden' : isPoints || !cartGoodsAmount || memberId || cartOilAmount || isCommonCard }"
             class="payway"
             @click="handlePayWayClick('gift')">
          <div class="icon">
            <img alt="" src="@/assets/icons/free.svg">
          </div>
          <div class="name">赠送</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div v-waves :class="{'forbidden' : isCommonCard || cartOilAmount|| !memberId }" class="payway"
             @click="handlePayWayClick('pointExchange')">
          <div class="icon">
            <img alt="" src="@/assets/icons/memberPoints.svg">
          </div>
          <div class="name">积分兑换</div>
        </div>
      </el-col>

    </el-row>
    <el-row :gutter="10" align="middle" justify="center" type="flex">
      <el-col :span="4">
        <div v-waves :class="{'forbidden' : memberId || cartGoodsAmount || isCommonCard }" class="payway"
             @click="handlePayWayClick('tuanyou')">
          <div class="icon">
            <img alt="" src="@/assets/icons/tuanyou.png">
          </div>
          <div class="name">团油F7</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div v-waves :class="{'forbidden' : isPoints || memberId || cartGoodsAmount || isCommonCard }" class="payway"
             @click="handlePayWayClick('didi')">
          <div class="icon">
            <img alt="" src="@/assets/icons/didi.svg">
          </div>
          <div class="name">滴滴F8</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div v-waves :class="{'forbidden' : memberId || cartGoodsAmount || isCommonCard}" class="payway"
             @click="handlePayWayClick('ejiayou')">
          <div class="icon">
            <img alt="" src="@/assets/icons/ejiayou.svg">
          </div>
          <div class="name">易加油F9</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div v-waves :class="{'forbidden' : memberId || cartGoodsAmount || isCommonCard}" class="payway"
             @click="handlePayWayClick('oldcard')">
          <div class="icon">
            <img alt="" src="@/assets/icons/oldcard.svg">
          </div>
          <div class="name">旧油卡</div>
        </div>
      </el-col>
      <el-col v-if="stationId === 1" :span="4">
        <div v-waves :class="{'forbidden' : memberId || cartGoodsAmount || isCommonCard }" class="payway"
             @click="handlePayWayClick('cnooc')">
          <div class="icon">
            <img alt="" src="@/assets/icons/cnooc.svg">
          </div>
          <div class="name">海油卡</div>
        </div>
      </el-col>
      <el-col v-else :span="4">
        <div v-waves :class="{'forbidden' : memberId || cartGoodsAmount || isCommonCard }" class="payway"
             @click="handlePayWayClick('chinaPetrolCard')">
          <div class="icon">
            <img alt="" src="@/assets/icons/china-petrol.svg">
          </div>
          <div class="name">中油卡</div>
        </div>
      </el-col>
      <el-col :span="4"></el-col>
    </el-row>
    <!-- 自用回罐授权 -->
    <check-authorize :checkKey="checkKey" :errMsg="errMsg" :showAuthDialog="showAuthDialog" @authPass="checkPass"
                     @hideAuthDialog="showAuthDialog = false"></check-authorize>
    <fast-pay-history :fuel-record-id="fuelRecordId" :visible="showFastPayHistory"
                      @hideHistory="showFastPayHistory = false"></fast-pay-history>
  </el-card>
</template>

<script>
import {mapGetters} from 'vuex'
import {cancelSplitOrder, deleteFuelRecord, queryPayResult, splitOrder} from '@/api/settle'
import {rsaEncrypt} from '@/utils/rsa'
import CheckAuthorize from './CheckAuthorize.vue'
import FastPayHistory from './FastPayHistory.vue'
import md5 from 'js-md5'
import moment from 'moment'
import {cartSettle} from '../../../api/settle'

var Mousetrap = require('mousetrap')
export default {
  name: 'CartRightFuctionArea',
  components: {
    CheckAuthorize,
    FastPayHistory
  },
  data () {
    return {
      // 查询次数
      queryTimes: 0,
      queryInterval: null,
      queryLoading: null,
      showAuthDialog: false,
      showFastPayHistory: false,
      fuelRecordId: '',
      checkKey: '',
      errMsg: '',
      remark: '',
      payWayName: {
        'ejiayou': '易加油',
        'didi': '滴滴',
        'miniprogram': '小程序',
        'gift': '赠送',
        'oilcard': '加油卡',
        'cash': '现金',
        'yinlian': '银联卡',
        'wechat': '微信',
        'alipay': '支付宝',
        'ecard': '旧电子卡',
        'oldcard': '旧油卡',
        'tuanyou': '团油',
        'pointExchange': '积分兑换',
        'cnooc': '海油卡',
        'chinaPetrolCard': '中油卡',
        'unpaid': '异常未收款'
      },
      dayList: [
        {
          id: 0,
          name: '周一'
        },
        {
          id: 1,
          name: '周二'
        },
        {
          id: 2,
          name: '周三'
        },
        {
          id: 3,
          name: '周四'
        },
        {
          id: 4,
          name: '周五'
        },
        {
          id: 5,
          name: '周六'
        },
        {
          id: 6,
          name: '周天'
        }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'cartList',
      'stationId',
      'memberId',
      'operator',
      'cartCash',
      'payWay',
      'amountOfCartList',
      'cartPayAmount',
      'oilPayAmount',
      'oilCouponDiscount',
      'goodsCouponDiscount',
      'couponDiscountAmount',
      'oilMemberDiscount',
      'selectedCouponList',
      'cartOilAmount',
      'cartGoodsAmount',
      'goodsPayAmount',
      'cartGoodsList',
      'cartOilList',
      'cardUid',
      'cardNo',
      'cardInfo',
      'systemDiscount',
      'goodsPromotionId',
      'cartVisible',
      'memberInfo',
      'customerDiscountList',
      'discountValid'
    ]),
    // 现金找零
    cashChange () {
      // 只有结算方式为现金时才返回数值差
      if (this.cartCash && this.cartCash > 0) {
        return (parseFloat(this.cartCash) - this.cartPayAmount).toFixed(2)
      }
      return ''
    },
    // 购物车中无库存商品名称
    goodsNameNoQuantity () {
      return this.cartGoodsList.filter(item => item.data.quantity <= 0).map(item => item.name).join(',')
    },
    // 显示撤销拆单按钮
    showCancelSplitOrder () {
      // 只有一笔加油记录且加油记录ID中带有"-s1"或"-s2"
      return this.cartGoodsList.length === 0 && this.cartOilList.length === 1 && this.isSplitOrder(this.cartOilList[0].id)
    },
    // 是储值卡且不是不记名优惠卡，也就是卡类型不为5
    isCommonCard () {
      return this.cardInfo && this.cardInfo.cardType !== 5
    },
    isPoints () {
      return this.cartList.length > 0 && this.cartList[0].name === '积分兑换'
    },
    // 储值卡结算后余额
    cardBalanceAfterPay () {
      if (this.cardUid) {
        return (this.cardInfo.balance - this.cartPayAmount).toFixed(2)
      } else {
        return 0.00
      }
    }
  },
  mounted () {
    this.bindKeyboard()
  },
  methods: {
    isSplitOrder (orderId) {
      return orderId.indexOf('s1') > -1 || orderId.indexOf('s2') > -1
    },
    keyboardInput (value) {
      console.log('keyboardInput:' + value)
      this.$store.dispatch('setCashOperation', value)
    },
    // 显示优惠券选择页面
    handleCouponDialogClick () {
      console.log('handleCouponDialogClick')
      this.$store.dispatch('showCouponDialog')
    },
    // 选择支付方式
    handlePayWayClick (payWay, confirm) {
      console.log('handlePayWayClick')
      console.log(payWay)
      if (this.isPoints && payWay !== 'pointExchange') {
        return false
      }
      if (this.isCommonCard && payWay !== 'oilcard') {
        return false
      }
      // 判断购物车中是否存在商品无库存
      if (this.goodsNameNoQuantity && !confirm) {
        this.$confirm('"' + this.goodsNameNoQuantity + '" 这些商品已无库存, 是否继续销售?', '库存提示', {
          confirmButtonText: '确定继续',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log('确定继续销售无库存商品')
          this.handlePayWayClick(payWay, true)
        }).catch(() => {
          return false
        })
        return false
      }
      if (payWay === 'wechat' || payWay === 'alipay' || payWay === 'paycode') {
        // 弹出支付码输入窗口
        this.$prompt('请扫描顾客支付码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType: 'password',
          closeOnClickModal: false,
          inputErrorMessage: '支付码不正确'
        }).then(({value}) => {
          console.log(value)
          // 判断支付码是微信还是支付宝
          payWay = this.getPayWayByAuthCode(value)
          if (!payWay) {
            this.$message.error('无效付款码！')
            return false
          }
          this.doCartSettle(payWay, value)
        }).catch(() => {
          console.log('取消扫码')
        })
      } else if (
        payWay === 'didi' ||
          payWay === 'chinaPetrolCard' ||
          payWay === 'miniprogram' ||
          payWay === 'ejiayou' ||
          payWay === 'ecard' ||
          payWay === 'oldcard' ||
          payWay === 'tuanyou' ||
          payWay === 'cnooc'
      ) {
        // 滴滴、中油卡、小程序只有非会员状态下可用，且可手动修改支付金额
        if (this.memberId) {
          this.$message.error('会员无法使用当前支付方式！')
          return false
        }
        // 购物车中没有加油记录时不允许使用这些支付方式
        if (this.cartGoodsAmount) {
          this.$message.error('当前支付方式只允许用于油品结算！')
          return false
        }
        const customerDiscount = Number(this.handleCustomerDiscount(this.payWayName[payWay], this.cartList[0].data.fuelName))
        let amountValue = this.cartOilAmount
        if (customerDiscount !== 0) {
          amountValue = (((Number(this.cartList[0].price)) - customerDiscount).toFixed(2) * this.cartList[0].data.litre).toFixed(2)
        }
        this.$prompt('支付结算金额', '确认支付金额并结算', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType: 'number',
          inputValue: amountValue,
          inputErrorMessage: '数字格式不正确'
        }).then(({value}) => {
          // 如果结算金额比应付金额大，要提示
          if (parseFloat(value) > parseFloat(this.cartOilAmount)) {
            this.$message.error('支付金额比应付金额大！')
            return false
          }
          this.$store.dispatch('setOilDiscountAmount', (this.cartOilAmount - value).toFixed(2))
          setTimeout(() => {
            this.doCartSettle(payWay, '')
          }, 200)
        }).catch(() => {
          this.$store.dispatch('setOilDiscountAmount', 0.00)
        })
      } else if (payWay === 'oilcard') {
        // 加油卡
        if (this.cardInfo && this.cardInfo.id && this.cartOilAmount > 0.0 && this.cartGoodsAmount <= 0.0) {
          // 判断可用油品
          if (this.cardInfo.usableFuelNames.indexOf(this.cartOilList[0].data.fuelName) === -1) {
            this.$message.warning('该油卡不适用于该油品！')
            return false
          }
          if (this.cardInfo.usableStationIds.split(',').indexOf(this.stationId + '') === -1) {
            this.$message.warning('该油卡不适用于该油站！')
            return false
          }
          // 判断卡余额是否足够支付，* 100转成整数来比较避免小数相等时返回不相等
          if (parseInt(this.cardInfo.balance * 100) < parseInt(this.cartPayAmount * 100)) {
            this.$message.warning('该油卡余额不足！')
            return false
          }
          // 弹窗确认密码
          if (this.cardInfo.password === md5('666666')) {
            this.doCartSettle(payWay, '')
          } else {
            this.$prompt('请输入支付密码', '确认支付密码', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputType: 'password',
              inputValue: '',
              inputErrorMessage: '密码格式不正确'
            }).then(({value}) => {
              console.log(value)
              if (md5(value) === this.cardInfo.password) {
                this.doCartSettle(payWay, '')
              } else {
                console.log(md5(value))
                console.log(this.cardInfo.password)
                this.$message.warning('支付密码不正确！')
              }
            }).catch(() => {
            })
          }
        } else {
          this.$message.warning('尚未识别到卡号，或尚未选择加油记录，或选了非油商品！')
        }
        return false
      } else if (payWay === 'gift') {
        // 购物车中有加油记录的时候不允许使用赠送功能
        if (this.cartOilAmount) {
          this.$message.error('油品消费不能执行赠送操作！')
          return false
        }
        this.$confirm('是否确认赠送？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 赠送时实际支付金额为0
          this.doCartSettle('gift', '')
        }).catch(() => {
          console.log('取消')
        })
      } else if (payWay === 'pointExchange') {
        if (this.cartOilAmount) {
          this.$message.error('油品消费不能执行积分兑换操作！')
          return false
        }
        if (this.memberInfo.totalPoints < this.cartPayAmount) {
          const difference = ((this.cartPayAmount) - this.memberInfo.totalPoints).toFixed()
          this.$message.error('该顾客积分不够消费商品，还差' + difference + '积分')
          return false
        }
        if (!(Math.floor(this.cartPayAmount) === this.cartPayAmount)) {
          this.$message.error('商品价格不能为小数！')
          return false
        }
        this.doCartSettle('pointExchange', '')
      } else if (payWay === 'unpaid') {
        this.$prompt('异常未收款', '请输入备注信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: ''
        }).then(({value}) => {
          this.remark = value
          setTimeout(() => {
            this.doCartSettle(payWay, '')
          }, 200)
        }).catch(() => {
        })
      } else {
        // 弹窗确认一下是否执行支付
        this.$confirm('是否确认使用【' + this.payWayName[payWay] + '】支付？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.doCartSettle(payWay, '')
        }).catch(() => {
        })
      }
    },
    // 执行购物车结算
    doCartSettle (payWay, paymentCode) {
      var cart = {
        operateTime: new Date(),
        cartList: this.cartList,
        stationId: this.stationId, // 油站ID
        memberId: this.memberId, // 会员ID
        operator: this.operator, // 操作员
        paymentType: payWay, // 支付方式
        paymentCode: paymentCode ? rsaEncrypt(paymentCode) : '', // 支付码（RSA加密后）
        cardUid: this.isCommonCard ? this.cardUid : '', // 储值卡ID
        cardNo: this.isCommonCard ? this.cardNo : '', // 储值卡编号
        amount: this.amountOfCartList.toFixed(2), // 应付金额
        payAmount: this.cartPayAmount.toFixed(2), // 支付金额
        oilCouponAmount: this.oilCouponDiscount,
        oilCouponIds: this.selectedCouponList.filter(item => (item.couponType + '') !== '7').map(item => item.id).join(','),
        oilPayAmount: this.oilPayAmount,
        oilAmount: this.cartOilAmount,
        goodsAmount: this.cartGoodsAmount,
        goodsPayAmount: this.goodsPayAmount,
        goodsCouponIds: this.selectedCouponList.filter(item => (item.couponType + '') === '7').map(item => item.id).join(','),
        goodsCouponAmount: 0.00,
        goodsPromotionId: this.goodsPromotionId,
        channel: payWay === 'pointExchange' ? 2 : '',
        remark: this.remark
      }
      console.log(cart)
      // 如果是会员或者储值卡结算 判断该笔订单是否有获取到优惠信息
      if (cart.memberId || cart.cardUid) {
        var tmpList = this.cartList.filter(item => item.type === 'oil')
        if (tmpList.length > 0) {
          console.log(this.discountValid)
          if ((this.discountValid.id !== this.memberId || this.discountValid.id !== this.cardUid) && !this.discountValid.valid) {
            this.$message.error('网络故障，未获取到优惠信息，请重试！')
            return
          }
        }
      }
      cartSettle(cart).then((res) => {
        console.log(res)
        if (res.data && res.data.status === 'done') {
          this.$message.success('支付成功！')
          this.$store.dispatch('hideCartDialog')
        } else if (res.data && res.data.status === 'doing') {
          console.log(res.data)
          console.log(res.data.paymentNo)
          console.log('需要定时查询支付结果')
          this.getCartSettleResult(res.data.paymentNo)
        }
      }).catch((err) => {
        console.log(err)
        this.$message.error(err || '请求出错')
      })
    },
    // 挂单
    handlePending () {
      console.log('handlePending')
      // 判断当前是否有选中油品，只有非油才允许挂单操作
      if (this.cartOilAmount > 0) {
        this.$prompt('异常未收款', '请输入备注信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: ''
        }).then(({value}) => {
          this.remark = value
          setTimeout(() => {
            this.doCartSettle('unpaid', '')
          }, 200)
        }).catch(() => {
        })
        return false
      }
      this.$store.dispatch('showPendingOrderDialog')
    },
    // 回罐
    handleBackToTank () {
      console.log('handleBackToTank')
      // 回罐时不允许购物车中有非油商品，如有则提示报错
      if (this.cartGoodsAmount > 0) {
        this.$message.warning('该操作不允许包含非油商品')
        return false
      }
      this.$confirm('是否确认回罐？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 回罐时实际支付金额为0
        this.doCartSettle('huiguan', '')
      }).catch(() => {
        console.log('取消')
      })
    },
    handleSelfUse () {
      console.log('handleSelfUse')
      // 回罐时不允许购物车中有非油商品，如有则提示报错
      if (this.cartGoodsAmount > 0) {
        this.$message.warning('该操作不允许包含非油商品')
        return false
      }
      this.$confirm('是否确认自用结算？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 回罐时实际支付金额为0
        this.doCartSettle('ziyong', '')
      }).catch(() => {
        console.log('取消')
      })
    },
    // 定时获取支付结果
    getCartSettleResult (paymentNo) {
      this.queryTimes = 0
      this.queryLoading = this.$loading({text: '结果查询中...'})
      this.queryInterval = setInterval(() => {
        if (this.queryTimes > 200) {
          // 查询次数到达上限，提示支付超时，停止定时查询
          this.$message.warning('支付结果查询超时')
          window.clearInterval(this.queryInterval)
          return false
        }
        this.queryTimes = this.queryTimes + 1
        queryPayResult({stationId: this.stationId, paymentNo: paymentNo}).then(res => {
          console.log('queryPayResult:' + paymentNo + ':' + res.data.status)
          if (res.data && res.data.status === 'done') {
            window.clearInterval(this.queryInterval)
            this.queryLoading.close()
            // 支付成功
            this.$message.success('支付成功！')
            this.$store.dispatch('hideCartDialog')
          } else if (res.data && res.data.status === 'error') {
            this.queryLoading.close()
            // 支付失败
            window.clearInterval(this.queryInterval)
            this.$alert(res.data.message || '支付失败！', '支付失败', {type: 'error'})
          }
        }).catch(err => {
          console.log(err)
        })
      }, 1000)
    },
    // 执行拆单操作
    handleSplitOrder () {
      // 判断当前购物车是否只有一笔加油记录
      if (this.cartGoodsList.length > 0) {
        this.$message.warning('购物车中有非油商品无法进行拆单！')
        return false
      }
      if (this.cartOilList.length !== 1) {
        this.$message.warning('购物车中没有加油记录无法进行拆单！')
        return false
      }
      console.log(this.cartOilList)
      // 弹出窗口，输入其中一笔的金额
      this.$prompt('请输入其中一笔金额', '拆单操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'number',
        inputValue: this.cartOilAmount,
        inputErrorMessage: '数字格式不正确'
      }).then(({value}) => {
        console.log(value)
        console.log(typeof value)
        if (value && parseFloat(value) < parseFloat(this.cartOilAmount) && parseFloat(value) > 0) {
          splitOrder({
            stationId: this.stationId,
            id: this.cartOilList[0].id,
            operator: this.operator,
            amount: value
          }).then(res => {
            console.log(res)
            this.$message.success(res.msg || '拆单成功！')
            this.$store.dispatch('hideCartDialog')
          }).catch(err => {
            console.log(err)
            this.$message.error(err || '拆单失败！')
          })
        } else {
          this.$message.warning('拆单金额必须大于0且小于油机金额！')
        }
      }).catch(() => {
        console.log('取消操作')
      })
    },
    cancelSplitOrder () {
      console.log('cancelSplitOrder')
      // 判断当前购物车是否只有一笔加油记录
      if (this.cartGoodsList.length > 0) {
        this.$message.warning('购物车中有非油商品无法进行拆单！')
        return false
      }
      if (this.cartOilList.length !== 1) {
        this.$message.warning('购物车中没有加油记录无法进行拆单！')
        return false
      }
      cancelSplitOrder({
        stationId: this.stationId,
        id: this.cartOilList[0].id,
        operator: this.operator
      }).then(res => {
        this.$message.success(res.msg || '撤销拆单成功！')
        this.$store.dispatch('hideCartDialog')
      }).catch(err => {
        console.log(err)
        this.$message.error(err || '撤销拆单失败！')
      })
    },
    checkSelfUse () {
      this.checkKey = 'pos-client.ziyong'
      this.errMsg = '该账户无【自用】权限'
      this.showAuthDialog = true
    },
    checkBackToTank () {
      this.checkKey = 'pos-client.huiguan'
      this.errMsg = '该账户无【回罐】权限'
      this.showAuthDialog = true
    },
    checkOthers () {
      this.checkKey = 'pos-client.others'
      this.errMsg = '该账户无【其他】结算权限'
      this.showAuthDialog = true
    },
    checkPass () {
      if (this.checkKey === 'pos-client.ziyong') {
        this.handleSelfUse()
      } else if (this.checkKey === 'pos-client.huiguan') {
        this.handleBackToTank()
      } else if (this.checkKey === 'pos-client.delete-order') {
        this.handleDeleteFuelRecord()
      } else if (this.checkKey === 'pos-client.other') {
        this.handleOthers()
      }
    },
    getPayWayByAuthCode (authCode) {
      // 微信：用户付款码条形码规则：18位纯数字，以10、11、12、13、14、15开头
      // 支付宝：支付授权码，25~30开头的长度为16~24位的数字，实际字符串长度以开发者获取的付款码长度为准
      var size = authCode.length
      if (size > 15) {
        var prefix = parseInt(authCode.substring(0, 2))
        console.log(prefix)
        if (prefix > 24 && prefix < 31 && size > 15 && size < 31) {
          return 'alipay'
        }
        if (prefix > 9 && prefix < 16 && size === 18) {
          return 'wechat'
        }
      }
      return ''
    },
    bindKeyboard () {
      Mousetrap.bind('f3', () => {
        if (this.cartVisible) {
          this.handlePayWayClick('paycode')
        }
      })
      Mousetrap.bind('f4', () => {
        if (this.cartVisible) {
          this.handlePayWayClick('yinlian')
        }
      })
      Mousetrap.bind('f6', () => {
        if (this.cartVisible) {
          this.handlePayWayClick('cash')
        }
      })
      Mousetrap.bind('f7', () => {
        if (this.cartVisible) {
          this.handlePayWayClick('tuanyou')
        }
      })
      Mousetrap.bind('f8', () => {
        if (this.cartVisible) {
          this.handlePayWayClick('didi')
        }
      })
      Mousetrap.bind('f9', () => {
        if (this.cartVisible) {
          this.handlePayWayClick('ejiayou')
        }
      })
    },
    checkDeleteFuelRecord () {
      this.checkKey = 'pos-client.delete-order'
      this.errMsg = '该账户无【消单】权限'
      this.showAuthDialog = true
    },
    handleOthers () {
      console.log('handleOthers')
      // 其他结算时不允许购物车中有非油商品，如有则提示报错
      if (this.cartGoodsAmount > 0) {
        this.$message.warning('该操作不允许包含非油商品')
        return false
      }
      this.$confirm('是否确认其他结算方式？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 其他结算实际支付金额为0
        this.doCartSettle('others', '')
      }).catch(() => {
        console.log('取消')
      })
    },
    handleDeleteFuelRecord () {
      // 判断当前购物车是否只有一笔加油记录
      if (this.cartGoodsList.length > 0) {
        this.$message.warning('购物车中有非油商品无法进行拆单！')
        return false
      }
      if (this.cartOilList.length !== 1) {
        this.$message.warning('购物车中没有加油记录无法进行拆单！')
        return false
      }
      console.log(this.cartOilList)
      this.$confirm('是否确认消单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteFuelRecord(this.cartOilList[0].data).then(res => {
          console.log(res)
          this.$message.success(res.msg || '消单成功！')
          this.$store.dispatch('hideCartDialog')
        }).catch(err => {
          console.log(err)
          this.$message.error(err || '消单失败！')
        })
      }).catch(() => {
        console.log('取消')
      })
    },
    showAmountCheckList () {
      console.log('showAmountCheckList')
      if (this.cartOilList.length !== 1) {
        this.$message.warning('购物车中没有加油记录！')
        return false
      }
      this.fuelRecordId = this.cartOilList[0].id
      this.showFastPayHistory = true
    },
    handleCustomerDiscount (customerType, cartOilType) {
      for (let i = 0; i < this.customerDiscountList.length; i++) {
        const customerDiscount = this.customerDiscountList[i]
        const nowHour = moment().hours()
        const nowDay = moment(new Date()).weekday()
        // 判断客户类型
        if (customerDiscount.customerType === customerType) {
          // 判断油品
          if (customerDiscount.enableOilType.indexOf(cartOilType) >= 0) {
            // 判断星期
            for (let j = 0; j < this.dayList.length; j++) {
              const day = this.dayList[j]
              if (customerDiscount.enableDay.indexOf(day.name) >= 0) {
                if (nowDay === day.id) {
                  // 判断时间
                  // 1.判断是否跨天
                  const startHour = Number(customerDiscount.startHour)
                  const endHour = Number(customerDiscount.endHour)
                  if (startHour > endHour) {
                    // 如果跨天的话那就是 开始时间 < 现在时间  && 现在时间 < 结束时间
                    if (startHour <= nowHour || nowHour < endHour) {
                      return customerDiscount.discount
                    }
                  } else {
                    if (startHour <= nowHour && nowHour < endHour) {
                      return customerDiscount.discount
                    }
                  }
                }
              }
            }
          }
        }
      }
      return 0
    }

  },
  beforeDestroy () {
    console.log('beforeDestroy')
    window.clearInterval(this.queryInterval)
  }
}
</script>

<style scoped>
.box-card {
  padding: 10px;
}

.box-card .info-item {
  padding-left: 10px;
  height: 30px;
  line-height: 30px;
}

.box-card .info-item span {
  color: orangered;
}

.info-item strong {
  font-size: 1.4rem;
}

.coupon {
  cursor: pointer;
}

.btn-item {
  font-size: 1.4rem;
  font-weight: bold;
  background: #409EFF;
  color: white;
  text-align: center;
  width: auto;
  height: 40px;
  line-height: 40px;
  border-radius: 3px;
  cursor: pointer;
}

.btn-danger {
  background: #909399;
  color: white;
}

.payway {
  width: 50px;
  height: 45px;
  text-align: center;
  border-radius: 4px;
  background: #ecf5ff;
  padding: 5px;
  cursor: pointer;
}

.forbidden {
  cursor: not-allowed;
  filter: grayscale(100%);
  color: lightgrey;
}

.payway .icon {
  height: 30px;
}

.payway .name {
  padding-top: 2px;
  line-height: 15px;
  font-size: 12px;
}

.payway .icon img {
  height: 25px;
  width: 40px;
}
</style>
<style>
.box-card .el-row {
  margin-bottom: 10px;
}

.box-card .el-button--small {
  padding: 10px;
}
</style>
